@echo off
chcp 65001 >nul
title AIOT智能学习桌系统启动器

echo.
echo ============================================
echo   🤖 AIOT智能学习桌系统启动器 v2.0
echo ============================================
echo.

:: 检查Python是否安装
python --version >nul 2>&1
if errorlevel 1 (
    echo ❌ 错误: 未检测到Python环境!
    echo 请先安装Python 3.8或更高版本
    echo 下载地址: https://www.python.org/downloads/
    pause
    exit /b 1
)

:: 显示Python版本
echo ✅ Python环境检测通过
for /f "tokens=2" %%i in ('python --version 2^>^&1') do echo    版本: %%i
echo.

:: 检查必要的库
echo 🔍 检查必要库文件...
python -c "import cv2, mediapipe, serial, numpy, requests, websockets, asyncio" 2>nul
if errorlevel 1 (
    echo ⚠️  检测到缺少必要库，正在自动安装...
    echo.
    pip install opencv-python mediapipe pyserial numpy requests websockets asyncio
    if errorlevel 1 (
        echo ❌ 库安装失败，请手动执行以下命令:
        echo pip install opencv-python mediapipe pyserial numpy requests websockets asyncio
        pause
        exit /b 1
    )
    echo ✅ 库安装完成
) else (
    echo ✅ 所有必要库已就绪
)
echo.

:: 检查硬件连接
echo 🔌 检查硬件连接状态...
python -c "
import serial.tools.list_ports
ports = list(serial.tools.list_ports.comports())
found_device = False
for port in ports:
    if 'USB' in port.description or 'CH340' in port.description or 'CP210' in port.description:
        print(f'  ✅ 发现设备: {port.device} ({port.description})')
        found_device = True
if not found_device:
    print('  ⚠️  未检测到EBP3901设备，请检查USB连接')
" 2>nul
echo.

:: 检查摄像头
echo 📷 检查摄像头状态...
python -c "
import cv2
cap = cv2.VideoCapture(0)
if cap.isOpened():
    print('  ✅ 摄像头连接正常')
    cap.release()
else:
    print('  ⚠️  摄像头连接异常，请检查USB连接')
" 2>nul
echo.

:: 创建必要目录
echo 📁 准备系统目录...
if not exist "logs" mkdir logs
if not exist "data" mkdir data
if not exist "backups" mkdir backups
echo ✅ 目录准备完成
echo.

:: 启动选项菜单
:menu
echo ============================================
echo   请选择启动模式:
echo ============================================
echo   1. 完整系统启动 (推荐)
echo   2. 仅硬件测试模式
echo   3. 仅摄像头测试模式
echo   4. 系统诊断模式
echo   5. 查看系统日志
echo   6. 退出
echo ============================================
set /p choice=请输入选项 (1-6): 

if "%choice%"=="1" goto start_full_system
if "%choice%"=="2" goto test_hardware
if "%choice%"=="3" goto test_camera
if "%choice%"=="4" goto system_diagnosis
if "%choice%"=="5" goto view_logs
if "%choice%"=="6" goto exit
echo 无效选项，请重新输入
goto menu

:start_full_system
echo.
echo 🚀 启动完整智能学习桌系统...
echo ============================================
echo   系统启动中，请稍候...
echo   - 硬件连接检查
echo   - 摄像头初始化
echo   - AI模块加载
echo   - 网络连接建立
echo ============================================
echo.
echo 💡 提示: 
echo   - 请确保EBP3901已连接并正常工作
echo   - 系统启动后将显示详细日志信息
echo   - 按 Ctrl+C 可安全退出系统
echo.
pause

:: 启动主程序
python "智能学习桌完整系统.py"
if errorlevel 1 (
    echo.
    echo ❌ 系统启动失败!
    echo 请检查配置文件和硬件连接
    echo 查看日志文件获取详细错误信息: logs\smart_desk_system.log
    pause
)
goto menu

:test_hardware
echo.
echo 🔧 硬件测试模式...
echo ============================================
python -c "
import serial.tools.list_ports
import time

print('扫描可用串口设备:')
ports = list(serial.tools.list_ports.comports())
for i, port in enumerate(ports, 1):
    print(f'  {i}. {port.device} - {port.description}')

if ports:
    try:
        choice = int(input('\n请选择要测试的端口编号: ')) - 1
        if 0 <= choice < len(ports):
            port_name = ports[choice].device
            print(f'\n尝试连接到 {port_name}...')
            import serial
            ser = serial.Serial(port_name, 115200, timeout=1)
            print('✅ 串口连接成功!')
            print('正在监听数据 (10秒)...')
            start_time = time.time()
            while time.time() - start_time < 10:
                if ser.in_waiting:
                    data = ser.readline().decode('utf-8', errors='ignore').strip()
                    if data:
                        print(f'接收: {data}')
                time.sleep(0.1)
            ser.close()
            print('串口测试完成')
        else:
            print('无效的端口选择')
    except Exception as e:
        print(f'串口测试失败: {e}')
else:
    print('未找到可用的串口设备')
"
echo.
pause
goto menu

:test_camera
echo.
echo 📷 摄像头测试模式...
echo ============================================
python -c "
import cv2
import time

print('正在测试摄像头...')
for i in range(3):
    cap = cv2.VideoCapture(i)
    if cap.isOpened():
        print(f'✅ 摄像头 {i} 可用')
        ret, frame = cap.read()
        if ret:
            h, w = frame.shape[:2]
            print(f'   分辨率: {w}x{h}')
            print('   正在显示预览 (按 q 退出)...')
            
            start_time = time.time()
            while time.time() - start_time < 10:
                ret, frame = cap.read()
                if ret:
                    cv2.imshow(f'Camera {i} Test', frame)
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        break
                else:
                    break
            cv2.destroyAllWindows()
        cap.release()
        break
    else:
        print(f'❌ 摄像头 {i} 不可用')
        cap.release()
else:
    print('未找到可用的摄像头设备')
"
echo.
pause
goto menu

:system_diagnosis
echo.
echo 🔍 系统诊断模式...
echo ============================================
python -c "
import sys
import os
import platform
import subprocess

print('🖥️  系统信息:')
print(f'   操作系统: {platform.system()} {platform.release()}')
print(f'   Python版本: {sys.version}')
print(f'   工作目录: {os.getcwd()}')
print()

print('📦 已安装的相关库:')
required_packages = ['opencv-python', 'mediapipe', 'pyserial', 'numpy', 'requests', 'websockets']
for package in required_packages:
    try:
        result = subprocess.run([sys.executable, '-m', 'pip', 'show', package], 
                              capture_output=True, text=True, timeout=10)
        if result.returncode == 0:
            version = [line for line in result.stdout.split('\n') if line.startswith('Version:')]
            if version:
                print(f'   ✅ {package}: {version[0].split(': ')[1]}')
            else:
                print(f'   ✅ {package}: 已安装')
        else:
            print(f'   ❌ {package}: 未安装')
    except Exception as e:
        print(f'   ⚠️  {package}: 检查失败 ({e})')
print()

print('📁 文件系统检查:')
files_to_check = [
    '智能学习桌完整系统.py',
    'config.py',
    'Arduino测试代码/SmartDesk_Main.ino',
    '摄像头坐姿检测模块/camera_posture.py'
]
for file_path in files_to_check:
    if os.path.exists(file_path):
        size = os.path.getsize(file_path)
        print(f'   ✅ {file_path} ({size} 字节)')
    else:
        print(f'   ❌ {file_path} (文件不存在)')
print()

print('🔌 硬件连接检查:')
try:
    import serial.tools.list_ports
    ports = list(serial.tools.list_ports.comports())
    if ports:
        for port in ports:
            print(f'   🔌 {port.device}: {port.description}')
    else:
        print('   ⚠️  未检测到串口设备')
except Exception as e:
    print(f'   ❌ 串口检查失败: {e}')

try:
    import cv2
    cap = cv2.VideoCapture(0)
    if cap.isOpened():
        print('   📷 摄像头: 可用')
        cap.release()
    else:
        print('   ❌ 摄像头: 不可用')
except Exception as e:
    print(f'   ❌ 摄像头检查失败: {e}')
"
echo.
pause
goto menu

:view_logs
echo.
echo 📋 查看系统日志...
echo ============================================
if exist "logs\smart_desk_system.log" (
    echo 最新日志内容 (最后20行):
    echo ----------------------------------------
    powershell "Get-Content 'logs\smart_desk_system.log' | Select-Object -Last 20"
    echo ----------------------------------------
) else (
    echo ⚠️  日志文件不存在，系统可能尚未运行过
)
echo.
echo 📁 可用日志文件:
dir /b logs\*.log 2>nul || echo    (无日志文件)
echo.
pause
goto menu

:exit
echo.
echo 👋 感谢使用AIOT智能学习桌系统!
echo 如有问题，请查看操作指南或联系技术支持。
echo.
timeout /t 3 /nobreak >nul
exit /b 0 